import updateManager from './common/updateManager';
const util = require('utils/bluebirdRequest')
const wxLogin = util.wxPromisify(wx.login);
const wxCheckSession = util.wxPromisify(wx.checkSession);
const promiseRequest = util.wxPromisify(wx.request);
const _Promise = require("utils/bluebird.js");
const req = require('/utils/request.js');
// var fundebug = require('libs/fundebug.1.7.4.min.js');
// fundebug.init({
//   apikey: '345a32bde7821af60b33ad750fb276765ee69e365d048ae602c47d14f7907c9a'
// })
//wx55ac305017c7e7e3
//fc73bc9ce8bf6deff15233131ab211ea

//正式
// wxcb8d29c74c575159
// 4ff62cb1b9a2da5fd6479d345cebad0d
App({
  globalData: {
    servicePhone: '18989891168',
    miniVersion: '',
    tokenUrl: 'https://api.haofenche.cn/',
    serverUrl: 'https://api.haofenche.cn/',
    qrUrl: 'https://cp.haofenche.cn/',
    imageUrl: 'https://api.haofenche.cn/car_image/',
    appId: 'wxcb8d29c74c575159',
    hasCheckMobile: false,
    authTokenPromise: null,
    token: null,
    openid: '',
    userInfo: null,
    sysinfo: null,
    currentAuction: null,
    currentCar: null,
    partnerCode: '',

    admin: {
      userToken: '',
      userInfo: '',
      partnerCode: ''
    }
  },
  onLaunch: function (options) {
    var that = this;
    console.log("onlaunch", options)
    var url = decodeURIComponent(options.query.q);
    console.log(url);
    var urlAyy = url.split('?')
    var code = that.getQueryString('code', url);
    console.log("code:", code)
    if (code != null) this.globalData.partnerCode = code
    this.getUserData();
    this.checkForUpdate();
    const miniProgram = wx.getAccountInfoSync();
    this.globalData.miniVersion = miniProgram.miniProgram.envVersion + "-" + miniProgram.miniProgram.version
  },

  getUserData() {
    var that = this;
    wxCheckSession().then(function (res) {
      var openid = wx.getStorageSync('openid');
      console.log("checksession succcess", openid)
      if (openid != null && openid != '') {
        that.getUserInfo()
      } else {
        that.reWxLogin();
      }
    }).catch(() => {
      that.reWxLogin();
    })
  },
  reWxLogin() {
    var that = this;
    wxLogin()
      .then(function (data) {
        console.log("wxLogin data:" + JSON.stringify(data));
        if (data.code) {
          //使用code获取openid
          that.getUserOpenId(data.code).then(function (res) {
            console.log("getuseropenid res", res)
            that.getUserInfo()
          })
        } else {
          console.log("wxLogin error version:" + that.globalData.miniVersion, JSON.stringify(data))
          // fundebug.notify("wxLogin error version:" + that.globalData.miniVersion, JSON.stringify(data));
        }
      })
  },

  getOpenId() {
    console.log('start get openid')
    var that = this;

    return new _Promise(function (resolve, reject) {
      var s = "sss";

      resolve(s);
    })

    // wx.checkSession({
    //   success: function () {
    //     console.log("checksession succcess")
    //     var openid = wx.getStorageSync('openid');
    //     console.log('start getOpenId openid:', openid)
    //     if (openid == "" || openid == null || openid == undefined) {
    //       return that.login();
    //     } else {
    //       return openid;
    //     }
    //   },
    //   fail: function () { //session过期
    //     console.log("checksession fail")
    //     return that.login();
    //   }
    // });
  },
  login: function () {
    var that = this;
    return wxLogin()
      .then(function (data) {
        console.log("wxLogin data:" + JSON.stringify(data));
        if (data.code) {
          //使用code获取openid
          return that.getUserOpenId(data.code);
        } else {
          console.log("wxLogin error version:" + that.globalData.miniVersion, JSON.stringify(data))
          // fundebug.notify("wxLogin error version:" + that.globalData.miniVersion, JSON.stringify(data));
          return "";
        }
      })
  },



  authToken: function () {
    console.log('start authToken')
    var that = this;
    return new _Promise((resolve, reject) => {
      wx.checkSession({ //校验微信session
        success: function () {
          var token = wx.getStorageSync('token');
          console.log('start authToken token:', token)
          if (token == '' || token == null) {
            // fundebug.notify("authtoken wx.checkSession version:" + that.globalData.miniVersion, "token为空，重新登录");
            that.login().then(function (data) {
              resolve();
            });
          } else {
            //获取缓存给全局变量赋值
            var openid = wx.getStorageSync('openid');
            if (openid == "" || openid == null || openid == undefined) {
              // fundebug.notify("authtoken wx.checkSession version:" + that.globalData.miniVersion, "用户openid为空， 重新登录");
              //用户ID为空， 重新登录
              that.login().then(function (data) {
                resolve();
              });
            } else {
              that.getUserInfo()
              resolve();
            }
          }
        },
        fail: function () { //session过期
          console.log("authtoken wx.checkSession version:" + that.globalData.miniVersion, "用户登录已过期，重新登录")
          // fundebug.notify("authtoken wx.checkSession version:" + that.globalData.miniVersion, "用户登录已过期，重新登录");
          that.login().then(function (data) {
            resolve();
          });
        }
      })
    });
  },

  getUserOpenId: function (code) {
    var that = this;
    return promiseRequest({
      url: that.globalData.tokenUrl + '/car/user/login/openid?jsCode=' + code + "&partnerCode=" + this.globalData.partnerCode,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      enableHttp2: true
    }).then(function (data) {
      console.log('getUserOpenId 返回:', JSON.stringify(data));
      return new _Promise((resolve, reject) => {
        var res = data.data;
        if (res.code == 0) {
          that.globalData.openid = res.data;
          wx.setStorageSync('openid', res.data);
          resolve(res.data);
        } else {
          // fundebug.notify("getUserOpenId error2 version:" + that.globalData.miniVersion, JSON.stringify(data));
          reject();
        }
      })
    }).catch(function onRejected(error) {
      console.log('getUserOpenId error:', JSON.stringify(error));
      // fundebug.notify("getUserOpenId error1 version:" + that.globalData.miniVersion, JSON.stringify(error));
    })
  },

  getUserInfo: function () {
    var that = this;
    var openid = wx.getStorageSync('openid');
    console.log("getuserinfo", openid)
    return promiseRequest({
      url: that.globalData.tokenUrl + '/car/user/login/token?openid=' + openid,
      method: 'get',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      enableHttp2: true
    }).then(function (data) {
      console.log('getUserInfo 返回:', JSON.stringify(data));
      return new _Promise((resolve, reject) => {
        var res = data.data;
        if (res.code == 0) {
          getApp().globalData.token = res.data.token;
          getApp().globalData.userInfo = res.data.user;
          getApp().globalData.openid = res.data.user.openid;
          console.log("save user", getApp().globalData.userInfo)
          wx.setStorageSync('token', getApp().globalData.token);
          wx.setStorageSync('openid', res.data.user.openid);
          wx.setStorageSync('userInfo', JSON.stringify(getApp().globalData.userInfo));
          resolve();
          const currentPages = getCurrentPages();
          if (currentPages.length > 0) {
            if (typeof (currentPages[0].init) == 'function') {
              console.log("call page init")
              currentPages[0].init();
            }
          }
        } else if (res.code == -1) {
          wx.navigateTo({
            url: '/pages/usercenter/register/index?userType=-1'
          });
          const currentPages = getCurrentPages();
          if (currentPages.length > 0) {
            if (typeof (currentPages[0].init) == 'function') {
              console.log("call page init")
              currentPages[0].init();
            }
          }
        }
      })
    }).catch(function onRejected(error) {
      console.log('getUserInfo error:', JSON.stringify(error));
      // fundebug.notify("getUserInfo error1 version:" + that.globalData.miniVersion, JSON.stringify(error));
    })
  },
  getUserInfoByLocal: function () {
    var userInfoStr = wx.getStorageSync('userInfo');
    if (userInfoStr != null && userInfoStr != "") {
      var userInfo = JSON.parse(userInfoStr);
      return userInfo;
    }
    return null;
  },

  checkForUpdate: function () {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
        console.log("upload:", res)
        if (res.hasUpdate) {
          // 有新版本
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate();
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            //新版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线，请您删除当前小程序，重新搜索打开哟~'
            })
          })
        }
      })
    }
  },
  onNetworkStatusChange: function () {
    wx.onNetworkStatusChange(function (res) {
      console.log("res.isConnected", res.isConnected)
      console.log("res.networkType", res.networkType)
      if (!res.isConnected) {
        wx.showToast({
          title: "网络连接已断开，请检查您的网络设置",
          duration: 3000,
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: "您的网络已切换至" + res.networkType,
          duration: 3000,
          icon: 'none'
        })
      }
    })
    wx.onNetworkWeakChange(function (res) {
      if (res.weakNet) {
        wx.showToast({
          title: "您的网络状态非常弱，网络类型：" + res.networkType,
          duration: 3000,
          icon: 'none'
        })
      }
    })
  },
  onShow: function () {
    updateManager();
  },
  //获取url参数值
  getQueryString: function (param, url) { //param为要获取的参数名 注:获取不到是为null  
    var arr = url.split("?"); //分割域名和参数界限  
    if (arr.length > 1) {
      arr = arr[1].split("&"); //分割参数  
      for (var i = 0; i < arr.length; i++) {
        var tem = arr[i].split("="); //分割参数名和参数内容  
        if (tem[0] == param) {
          return tem[1];
        }
      }
      return null;
    } else {
      return null;
    }
  },
});
